package com.fy.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy.common.constant.RedisKeyConstant;
import com.fy.common.enums.ErrorType;
import com.fy.common.model.ResponseError;
import com.fy.common.model.im.UserOnlineStatus;
import com.fy.common.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@SuppressWarnings("all")
public class LoginInterceptor implements HandlerInterceptor {

    private static final String USER_ID = "userId";
    private static final String DEVICE = "device";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private void printWriter(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        ResponseError responseError = new ResponseError();
        responseError.setCode(ErrorType.USER_NOT_LOGIN.getErrorCode());
        responseError.setError(ErrorType.USER_NOT_LOGIN.getErrorKey());
        printWriter.write(JSON.toJSONString(responseError));
    }

    /**
     * interceprot 登录权限验证
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      /*  String token = TokenUtil.getToken(request);
        if(StringUtils.isNotBlank(token)){
            Long userId = TokenUtil.getParamsFromToken(token, USER_ID, Long.class);
            String device = TokenUtil.getParamsFromToken(token, DEVICE, String.class);
            Object userInfoStr = redisTemplate.opsForHash().get(RedisKeyConstant.USER_ONLINE_LIST + userId, device);
            if(userInfoStr == null){
                this.printWriter(response);
                return false;
            }
            UserOnlineStatus userInfo = JSONObject.parseObject(userInfoStr.toString(), UserOnlineStatus.class);
            if (token.equals(userInfo.getToken())) {
                return true;
            } else {
                this.printWriter(response);
                return false;
            }
        }else{
            printWriter(response);
            return false;
        }*/
      return true;
    }

}


